/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.fee.entity.PickAddress;
import com.jeeplus.modules.fee.entity.ShippingAddress;
import com.jeeplus.modules.fee.mapper.ShippingAddressMapper;
import com.jeeplus.modules.fee.service.PickAddressService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.fee.entity.Consignor;
import com.jeeplus.modules.fee.service.ConsignorService;

/**
 * 下游客户Controller
 * @author weisong
 * @version 2017-10-10
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/consignor")
public class ConsignorController extends BaseController {

	@Autowired
	private ConsignorService consignorService;
	@Autowired
	private ShippingAddressMapper mapper;
	
	@ModelAttribute
	public Consignor get(@RequestParam(required=false) String id) {
		Consignor entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = consignorService.get(id);
		}
		if (entity == null){
			entity = new Consignor();
		}
		return entity;
	}
	
	/**
	 * 结算方列表页面
	 */
	@RequiresPermissions("fee:consignor:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/consignorList";
	}
	
		/**
	 * 结算方列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:consignor:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Consignor consignor, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Consignor> page = consignorService.findPage(new Page<Consignor>(request, response), consignor); 
		return getBootstrapData(page);
	}
	/**
	 * 结算方列表数据(下拉框用)
	 */
	@ResponseBody
	@RequestMapping(value = "consignorList")
	public String consignorList() {
		List<Consignor> list = consignorService.findList(new Consignor());
		Gson gson=new Gson();
		return gson.toJson(list).toString();
	}


	/**
	 * 查看，增加，编辑结算方表单页面
	 */
	@RequiresPermissions(value={"fee:consignor:view","fee:consignor:add","fee:consignor:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Consignor consignor, Model model) {
		model.addAttribute("consignor", consignor);
		return "modules/fee/consignorForm";
	}

	/**
	 * 保存结算方
	 */
	@ResponseBody
	@RequiresPermissions(value={"fee:consignor:add","fee:consignor:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Consignor consignor, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, consignor)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
		consignorService.save(consignor);//保存
		j.setSuccess(true);
		j.setMsg("保存结算方成功");
		return j;
	}
	
	/**
	 * 删除结算方
	 */
	@ResponseBody
	@RequiresPermissions("fee:consignor:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Consignor consignor, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		consignorService.delete(consignor);
		j.setMsg("删除结算方成功");
		return j;
	}
	
	/**
	 * 批量删除结算方
	 */
	@ResponseBody
	@RequiresPermissions("fee:consignor:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			consignorService.delete(consignorService.get(id));
		}
		j.setMsg("删除结算方成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:consignor:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Consignor consignor, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "结算方"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Consignor> page = consignorService.findPage(new Page<Consignor>(request, response, -1), consignor);
    		new ExportExcel("结算方", Consignor.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出结算方记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public Consignor detail(String id) {
		return consignorService.get(id);
	}



	@ResponseBody
	@RequestMapping(value = "getCosignor")
	public String getById(String id) {
		Gson gson=new Gson();
		return gson.toJson(consignorService.get(id)).toString();
	}

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:consignor:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Consignor> list = ei.getDataList(Consignor.class);
			for (Consignor consignor : list){
				try{
					consignor.setRemarks(consignor.getBankAddress());
					consignorService.save(consignor);
					ShippingAddress s=new ShippingAddress();
					s.setAddress(consignor.getTaxPayerNo());
					s.setFeeConsignor(consignor);
					s.setPhone(consignor.getBankNo());
					s.setContacts(consignor.getBankName());
					s.setId(UUID.randomUUID().toString().replace("-",""));
					mapper.insert(s);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条结算方记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条结算方记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入结算方失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/consignor/?repage";
    }
	
	/**
	 * 下载导入结算方数据模板
	 */
	@RequiresPermissions("fee:consignor:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "结算方数据导入模板.xlsx";
    		List<Consignor> list = Lists.newArrayList(); 
    		new ExportExcel("结算方数据", Consignor.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/consignor/?repage";
    }
	

}